package org.scboy.common.dynamic.node.logicNode;

import org.scboy.common.annotation.ScriptNode;
import org.scboy.common.dynamic.node.BaseNode;
import org.scboy.utils.entitys.coobi.Model;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.expression.ExpressionUtil;
import cn.hutool.json.JSONObject;

@ScriptNode(value="LOGIC_IF")
public class LogicIfNode extends BaseNode {

	String expression=null;
	
	@Override
	public void create(JSONObject object) {
		expression=object.getStr("expression");
	}

	@Override
	public Object run() {
		/**
		 * 测试日志
		 */
		if(this.script.isTest()) {
			this.script.appendMsg("----->开始执行："+getNodeName()+" 节点ID："+this.getId());
		}
		
		if(StrUtil.isEmpty(expression)) {
			throw new RuntimeException(getNodeName()+"为逻辑节点，但是没有逻辑判断的表达式。");
		}

		//输出流
		BaseNode runYesTo = getRunTo("yes");

		BaseNode runNoTo = getRunTo("no");
		
		Model params=getSourceData("params", true, Model.class);
		
		try {
			boolean eval = (boolean)ExpressionUtil.eval(expression, params);
			if(eval) {
				
				/**
				 * 测试日志
				 */
				if(this.script.isTest()) {
					this.script.appendMsg("缓存数据：\r\n"+entityToString(this.getDataAll()));
					this.script.appendMsg("执行下个节点："+runYesTo.getNodeName()+" 节点ID："+runYesTo.getId());
				}
				
				return runYesTo.run();
			}else {
				
				/**
				 * 测试日志
				 */
				if(this.script.isTest()) {
					this.script.appendMsg("缓存数据：\r\n"+entityToString(this.getDataAll()));
					this.script.appendMsg("执行下个节点："+runNoTo.getNodeName()+" 节点ID："+runNoTo.getId());
				}
				
				return runNoTo.run();
			}
		} catch (Exception e) {
			throw new RuntimeException(getNodeName()+"表达式判断异常。",e);
		}
	}
}
